﻿using MediatR;
using W.Warehouse.Api.Application.Command.AllocationCommand;
using W.Warehouse.Domain.DTO;
using W.Warehouse.Repository.Interface;

namespace W.Warehouse.Api.Application.CommandHandlder.AllocationCommandHadler
{
    public class AllocationDeleteCommandHandler : IRequestHandler<AllocationDeleteCommand, int>
    {
        private readonly IAllocationRepository _iallocationRepository;
        private readonly IAllocationProductRepository _iallocationProductRepository;
        public AllocationDeleteCommandHandler(IAllocationRepository iallocationRepository, IAllocationProductRepository iallocationProductRepository)
        {
            _iallocationRepository = iallocationRepository;
            _iallocationProductRepository = iallocationProductRepository;
        }

        public async Task<int> Handle(AllocationDeleteCommand request, CancellationToken cancellationToken)
        {
            var alist = await _iallocationRepository.GetAllAsync();
            var aplist = await _iallocationProductRepository.GetAllAsync();
            var list = (from a in alist
                        join b in aplist
                        on a.AllocationId equals b.AllocationId
                        where b.AllocationProductId == request.AllocationProductId && a.IsDelete == false && b.IsDelete == false
                        select b).FirstOrDefault();
            if (list != null)
            {
                list.IsDelete = true;
            }
            return await _iallocationProductRepository.UpdateAsync(list);
        }
    }
}
